package com.noyes4j.common.utils.airkiss;

import com.alibaba.fastjson.JSONObject;
import com.noyes4j.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
* @Description:    微信air kiss 工具类
* @Author:         luoyhong
* @CreateDate:     2021/1/26 14:58
* @UpdateUser:     luoyhong
* @UpdateDate:     2021/1/26 14:58
* @UpdateRemark:   修改内容
* @Version:        1.0
*/
public class AirKissUtil {
/*

    private static Logger logger = LoggerFactory.getLogger(AirKissUtil.class);
    private static final String appid = "wx6ab5ee877d547d93";//"APPID";
    private static final String appsecret = "3c7b74ad556ad4025fa4c9d43e5a1106";//"APPSECRECT";
    //private static String localurl = "";//"当前文件的访问地址";
    private static final String acctokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid
            + "&secret=" + appsecret;
    private static final String ticketurl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?&type=jsapi&access_token=";
    private static String accessToken = "";
    private static String apiTicket = "";
*/

    /**
     * 计算字符串的hash值
     * @param string    明文
     * @param algorithm 算法名
     * @return          字符串的hash值
     */
    public static String hash(String string, String algorithm) {
        if (string.isEmpty()) {
            return "";
        }
        MessageDigest hash = null;
        try {
            hash = MessageDigest.getInstance(algorithm);
            byte[] bytes = hash.digest(string.getBytes("UTF-8"));
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getAccessToken(String accessTokenUrl){

        String accessToken = null;
        try{
            String acctokenResult = HttpUtil.doGet(accessTokenUrl);
            JSONObject acctokenJson = null;
            if(!StringUtils.isBlank(acctokenResult)){
                acctokenJson = JSONObject.parseObject(acctokenResult);
            }
            if (acctokenJson!=null&&acctokenJson.containsKey("access_token")) {
                accessToken = acctokenJson.getString("access_token");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return accessToken;
    }

    public static String getApiTicket(String prefixTicketUrl,String accessToken,String accessTokenUrl){

        String apiTicket = null;
        try {
            String ticketResult = HttpUtil.doGet(prefixTicketUrl + accessToken);
            JSONObject ticketjson = null;
            if(!StringUtils.isBlank(ticketResult)){
                    ticketjson = JSONObject.parseObject(ticketResult);
            }
            if(ticketjson!=null){
                int errcode = ticketjson.getInteger("errcode");
                if(0==errcode&&ticketjson.containsKey("ticket")){
                    apiTicket = ticketjson.getString("ticket");
                }else if(40001==errcode){//access_token失效重新获取
                    accessToken = null;
                    accessToken = getAccessToken(accessTokenUrl);
                    ticketResult = HttpUtil.doGet(prefixTicketUrl + accessToken);
                    if(!StringUtils.isBlank(ticketResult)){
                        ticketjson = JSONObject.parseObject(ticketResult);
                        if(ticketjson!=null&&0==ticketjson.getInteger("errcode")&&ticketjson.containsKey("ticket")){
                            apiTicket = ticketjson.getString("ticket");
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return apiTicket;
    }

    /*public static R getJsAPIConfig(JsApiConfigModel jsApiConfigModel) {

        try{
            if(StringUtils.isEmpty(localurl)){
                localurl = jsApiConfigModel.getLink();
            }
            //String timeStamp =  System.currentTimeMillis() / 1000 + "";
            String timeStamp =  System.currentTimeMillis()+"";
            String nonceStr = "";
            String sign = "";
            String openid = "";

            openid = getOpenId(jsApiConfigModel.getJsCode());
            if(StringUtils.isEmpty(openid)){
                return R.error("get openid is error");
            }
            if(StringUtils.isEmpty(accessToken)){
                accessToken = getAccessToken();
            }
            if(StringUtils.isEmpty(accessToken)){
                return R.error("get access_token error");
            }

            if(StringUtils.isEmpty(apiTicket)){
                apiTicket = getApiTicket();
            }
            if (StringUtils.isEmpty(apiTicket)) {
                return R.error("get ticket error");
            }
            System.out.println("apiTicket="+apiTicket);
            nonceStr = getRandomString(16);
            if(StringUtils.isBlank(nonceStr)){
                return R.error("get nonceStr error");
            }

            String key = "jsapi_ticket=" + apiTicket
                    + "&noncestr=" + nonceStr
                    + "&timestamp=" + timeStamp
                    + "&url=" + localurl;
            sign = hash(key, "SHA1");

            if(StringUtils.isBlank(sign)){
                return R.error("get sign error");
            }

            JSONObject qrJson =  new JSONObject();
            qrJson.put("s",jsApiConfigModel.getWifiSsid());
            qrJson.put("p",jsApiConfigModel.getWifiPwd());
            qrJson.put("o",openid);
            String qrContent = Base64Util.encode(qrJson.toJSONString());
            String qrcodePath  = QRCodeUtil.getPathByCodeCreate( qrContent,  QRCodeUtil.iotQrCodeBasePath,  null,  QRCodeUtil.logoPath) ;
            qrcodePath = qrcodePath.replace(QRCodeUtil.iotQrCodeBasePath,"");
            return R.data(qrcodePath);

        }catch (Exception e){
            logger.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }*/

    public static String getRandomString(int num){
        String str = UUID.randomUUID().toString().replace("-","");
        if(!StringUtils.isBlank(str)){
            if (str.length()>num) {
                str = str.substring(0,num);
            }
        }
        return str;
    }

    public static String getOpenId(String code,String appid,String appsecret) {

        String openid = null;
        try{
            if(!StringUtils.isEmpty(code)){
                //String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret + "&js_code=" + code + "&grant_type=authorization_code";
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
                // 发送请求，返回Json字符串
                String resultStr = HttpUtil.doGet(url);
                JSONObject jsonObject = new JSONObject();
                if(!StringUtils.isEmpty(resultStr)){
                    // 转成Json对象 获取openid
                    jsonObject = JSONObject.parseObject(resultStr);
                }
                if(jsonObject.containsKey("openid")){
                    openid = jsonObject.getString("openid");
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return openid;
    }

}
